package com.ng.oauth2.service.impl;

import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ng.common.utils.Constant;
import com.ng.config.SysConfig;
import com.ng.oauth2.service.OauthService;
import com.ng.sys.entity.SysUserEntity;
import com.ng.sys.service.SysMenuService;
import com.ng.sys.service.SysUserService;
import com.ng.sys.service.SysUserTokenService;

@Service
public class OauthServiceImpl implements OauthService {
  
	@Autowired
	private SysConfig sysConfig ;
	 
	
	@Autowired
	private SysUserService userService ;
	
	@Autowired
	private SysUserTokenService userTokenService ;
	
	@Autowired
	private SysMenuService menuService ;
	
 

	@Override 
	public SysUserEntity queryByToken(String token) {
		// TODO Auto-generated method stub
		if(StringUtils.isBlank(token))
			return null;
		
	/* 
		// 判断是否允许登录,不允许的话从表查,允许的话jwt解析 
		boolean rl= repeatLogin();
		String userId = null ;
 
		if(rl) {
			//jwt 解析
			Claims c = jwtUtils.getClaimByToken(token);
			if(c == null) {
				return null;
			}
			userId = c.getSubject();
			
			
		} else {

			userId = userTokenService.queryUserIdByToken(token);// oauthDao.selectUserIdByToken(token);
		
		}*/
		
		String userId = userTokenService.queryUserIdByToken(token);
		   
		if(userId == null ) return null; 
		
		if(StringUtils.isNotBlank(userId) && userId.equals(Constant.SUPER_ADMIN)) {
			return sysConfig.getAdminUser();
		}
		
		SysUserEntity user = userService.getById(userId);
		
		return user;
	}

	@Override 
	public Set<String> queryPermsBytoken(String token) {
		if(StringUtils.isBlank(token))
			return null;
		// TODO Auto-generated method stub
		
		// 取出token  基于token的缓存，重登录避免缓存 
		
	/*	boolean rl= repeatLogin();
		String userId = null;
		if(rl) {
			//jwt 解析
			Claims c = jwtUtils.getClaimByToken(token);
			if(c == null) {
				return null;
			}
			userId = c.getSubject();
			 
		} else {
			userId = userTokenService.queryUserIdByToken(token);// oauthDao.selectUserIdByToken(token);
		}*/
		 
		String userId = userTokenService.queryUserIdByToken(token);
		
		if(StringUtils.isBlank(userId))
			return null;
		
		Set<String> perms =  menuService.queryAllPerms(userId);
		 
		
		return perms ; 
		
	}
 
	/**
	 * 判断是否允许重复登录
	 * @return
	 */ 
	/*public Boolean repeatLogin() { 
		
		String key = getClass().getSimpleName() + ".repeatLogin";
		 
		if(redisUtils.containKey(key)) {
			return redisUtils.get(key, Boolean.class);
		}
		
		String rl = configService.getValue("repeat_login");
		
		Boolean ret = rl != null && (rl.trim().toLowerCase().equals("true") || rl.trim().equals("1"));
		 
		redisUtils.set(key, ret);
		
		return ret ;
	 
	}*/
	
}
